const Base = require('./base.js');
const ErrCode = require('../utils/errCode');
const Status = require('../utils/status');

function getNowTime(formatstr) {
    var date = new Date();
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' ';
    var h = date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':';
    var m = date.getMinutes() < 10 ? '0' + date.getMinutes() + ':' : date.getMinutes() + ':';
    var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    return Y + M + D + h + m + s;
}

module.exports = class extends Base {
    async getAllSubjectAction() {
        const { classid } = this.get();
        let rowDatas = await this.model('subject').where({ classid, userid: this.userInfo.id }).select();
        return this.success(rowDatas);
    }

    async addSubjectAction() {
        const { classid, subjectname, totaltimes } = this.post();
        try {
            let subjectid = await this.model('subject').add({... { classid, subjectname, totaltimes }, hastimes: 1, userid: this.userInfo.id });
            let students = await this.model('student').where({ classid }).select();
            students.forEach(async(item) => {
                await this.model('student_subject').add({ subjectid, classid, studentid: item.id, state: 1 });
            });
            return this.success(subjectid, "班级添加成功");
        } catch (err) {
            this.fail(ErrCode.SUBJECT_UPDATE_FAIL.code, ErrCode.SUBJECT_UPDATE_FAIL.msg);
        }
    }

    async updateSubjectAction() {
        const { subjectid, subjectname, totaltimes } = this.post();
        let res = await this.model('subject').where({ id: subjectid, userid: this.userInfo.id }).update({ subjectname, totaltimes });
        return this.success(res, Status.CLASS_UPDATE_SUCCESS);
    }

    async deleleSubjectAction() {
        const { subjectid, classid } = this.get();
        await this.model('student_subject').where({ subjectid }).delete();
        await this.model('subject').where({ classid, id: subjectid, userid: this.userInfo.id }).delete();
        return this.success('删除成功', Status.DELETE_CLASS_SUCCESS);
    }

    async getClassnameAndSubjectnameAction() {
        const { classid, subjectid } = this.post();
        let classname = await this.model('class').where({ id: classid }).getField('classname', true);
        let subjectname = await this.model('subject').where({ id: subjectid }).getField('subjectname', true);
        let hastimes = await this.model('subject').where({ id: subjectid }).getField('hastimes', true);
        let data = { classid, classname, subjectid, subjectname, hastimes }
        return this.success(data);
    }

    async getSubjectRecordAction() {
        const { classid, classname, subjectid, subjectname, hastimes } = this.post();
        const date = getNowTime('Y-M-D');
        let record = await this.model('subject_record').where({ classid, subjectid, times: hastimes }).find()
        if (JSON.stringify(record) === "{}") {
            let allStu = await this.model('student').where({ classid }).select();
            let insData = { classid, classname, subjectid, subjectname, date, times: hastimes, tasks: JSON.stringify({ tasks: [] }), signnum: 0, unsignnum: allStu.length, leavenum: 0, pointnum: 0, totalpoint: 0, tasksspeed: 0 }
            await this.model('subject_record').add({...insData });
            return this.success({...insData }, "课程记录初始化成功");
        } else {
            let data = await this.model('subject_record').where({ classid, subjectid, times: hastimes }).find();
            data.tasks = JSON.parse(data.tasks);
            return this.success(data, "课程记录获取成功");
        }

    }

    async initAllStudentSubjectRecordAction() {
        const { classid, classname, subjectid, subjectname, hastimes } = this.post();
        let studentList = await this.model('student').where({ classid }).select();
        let ssRecordList = await this.model('student_subject_record').where({ classid, subjectid, times: hastimes }).select();
        if (ssRecordList.length == 0) {
            studentList.forEach(async(item) => {
                await this.model('student_subject_record').add({
                    classid,
                    classname,
                    subjectid,
                    subjectname,
                    times: hastimes,
                    studentid: item.id,
                    studentname: item.studentname,
                    sign: -1,
                    point: 0,
                    comment: -1,
                    tasks: '',
                    pointnum: 0,
                    totalpoint: 0,
                    tasksspeed: 0,
                });
            });
            return this.success({}, "数据初始化成功");
        } else {
            return this.success({}, '下一步——获取数据');
        }

    }

    async getAllStudentSubjectRecordAction() {
        let { classid, subjectid, hastimes } = this.post();
        let subjectStates = await this.model('student_subject').where({ classid, subjectid }).select();
        let ssRecordList = await this.model('student_subject_record').where({ classid, subjectid, times: hastimes }).select();
        ssRecordList.forEach(item => {
            subjectStates.forEach(it => {
                if (item.studentid == it.studentid) {
                    switch (it.state) {
                        case 1:
                            item.state = '必修';
                            break;
                        case 2:
                            item.state = '选修';
                            break;
                        case 3:
                            item.state = '自修';
                            break;
                        case 4:
                            item.state = '免修';
                            break;
                    }
                }
            });
            item.tasks ? item.tasks = item.tasks.split(',') : item.tasks = [];
        });
        return this.success(ssRecordList, "数据获取成功");
    }

    async manualSignAction() {
        const { classid, subjectid, hastimes, studentid, sign } = this.post();
        const time = getNowTime();
        const timing = time.toString().split(' ')[1];
        try {
            await this.model('student_subject_record').where({ classid, subjectid, times: hastimes, studentid }).update({ sign, signtime: timing });
            this.calcSignSituation(classid, subjectid, hastimes);
            return this.success({}, "修改成功");
        } catch (error) {
            return this.success({}, "修改失败");
        }
    }

    async updateSignRemarkAction() {
        const { classid, subjectid, hastimes, studentid, signRemarks } = this.post();
        await this.model('student_subject_record').where({ classid, subjectid, times: hastimes, studentid }).update({ signRemarks });
        return this.success({}, "修改成功");
    }

    async getLessenTasksAction() {
        const { classid, subjectid, hastimes } = this.post();
        let res = await this.model('subject_record').where({ classid, subjectid, times: hastimes }).getField('tasks', true);
        let data = JSON.parse(res);
        return this.success(data.tasks, "课堂任务")
    }

    async addSubjectRecordTasksAction() {
        const { classid, subjectid, hastimes, newtask } = this.post();
        let oldtask = await this.model('subject_record').where({ classid, subjectid, times: hastimes }).getField('tasks', true);
        let data = JSON.parse(oldtask);
        data.tasks.push({ value: newtask, label: newtask, num: 0 });
        await this.model('subject_record').where({ classid, subjectid, times: hastimes }).update({ tasks: JSON.stringify(data) });
        this.calcCommentSituation(classid, subjectid, hastimes);
        return this.success({}, "添加成功");
    }

    async deleteSubjectRecordTasksAction() {
        const { classid, subjectid, hastimes, taskname } = this.post();
        let oldtask = await this.model('subject_record').where({ classid, subjectid, times: hastimes }).getField('tasks', true);
        let data = JSON.parse(oldtask);
        data.tasks = data.tasks.filter(item => {
            return item.label != taskname;
        });
        await this.model('subject_record').where({ classid, subjectid, times: hastimes }).update({ tasks: JSON.stringify(data) });
        this.calcCommentSituation(classid, subjectid, hastimes);
        return this.success({}, "删除成功");
    }

    async updateSubjectRecordPointAction() {
        const { classid, subjectid, hastimes, studentid, point } = this.post();
        await this.model("student_subject_record").where({ classid, subjectid, times: hastimes, studentid }).update({ point });
        this.calcCommentSituation(classid, subjectid, hastimes);
        return this.success({}, "加分点修改成功");
    }

    async updateSubjectRecordCommentAction() {
        const { classid, subjectid, hastimes, studentid, comment } = this.post();
        await this.model("student_subject_record").where({ classid, subjectid, times: hastimes, studentid }).update({ comment });
        return this.success({}, "表现评价修改成功");
    }

    async updateSubjectRecordStudentTasksAction() {
        const { classid, subjectid, times, studentid, tasks } = this.post();
        await this.model("student_subject_record").where({ classid, subjectid, times, studentid }).update({ tasks: tasks.toString() });
        this.calcCommentSituation(classid, subjectid, times);
        return this.success({}, "学生任务修改成功");
    }


    async updateCommentRemarkAction() {
        const { classid, subjectid, hastimes, studentid, commentRemarks } = this.post();
        await this.model('student_subject_record').where({ classid, subjectid, times: hastimes, studentid }).update({ commentRemarks });
        return this.success({}, "备注修改成功");
    }

    async endClassAction() {
        const { classid, subjectid, hastimes } = this.post();
        await this.model('subject').where({ classid, id: subjectid }).update({ hastimes: hastimes + 1 });
        return this.success({}, `第${hastimes}节结束`);
    }

    // 课堂表现 计算学生任务完成情况
    async calcCommentSituation(classid, subjectid, times) {
        let subject = await this.model('subject_record').where({ classid, subjectid, times }).find();
        let subject_tasksdata = JSON.parse(subject.tasks);
        let pointList = await this.model("student_subject_record").where({ classid, subjectid, times }).getField('point');
        let pointnum = 0;
        let totalpoint = 0;
        pointList.forEach((item) => {
            item > 0 && pointnum++;
            totalpoint += item;
        });
        let tasksList = await this.model("student_subject_record").where({ classid, subjectid, times }).getField('tasks');
        let finishnum = 0;
        subject_tasksdata.tasks.forEach(item => {
            item.num = 0
            tasksList.forEach(it => {
                if (it != null && it.includes(item.value)) item.num += 1;
            });
            finishnum += item.num;
        });
        let tasksspeed = Math.round(finishnum / (subject_tasksdata.tasks.length * tasksList.length) * 100);
        await this.model('subject_record').where({ classid, subjectid, times }).update({ tasks: JSON.stringify(subject_tasksdata), totalpoint, pointnum, tasksspeed })

    }

    // 方法名后面没添加Action  计算签到情况
    async calcSignSituation(classid, subjectid, times) {
        let ssRecord = await this.model("student_subject_record").where({ classid, subjectid, times }).select();
        let signnum = 0,
            unsignnum = 0,
            leavenum = 0;
        ssRecord.forEach(item => {
            switch (item.sign) {
                case -1:
                    unsignnum += 1;
                    break;
                case 0:
                    signnum += 1;
                    break;
                case 1:
                    leavenum += 1;
                    break;
            }
        });
        await this.model('subject_record').where({ classid, subjectid, times }).update({ signnum, unsignnum, leavenum });
    }

    // 第三个模块，查看记录

    async getSubjectInfoAction() {
        let { classid, subjectid } = this.post();
        let subjectInfo = await this.model('subject').where({ id: subjectid, classid }).find();
        return this.success(subjectInfo, "课程信息获取成功");
    }
};